package com.me.bbs.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.me.bbs.dto.UserFollowingDTO;
import com.me.bbs.entity.User;
import com.me.bbs.entity.UserFollowing;
import com.me.bbs.mapper.UserFollowingMapper;
import com.me.bbs.service.IUserFollowingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.me.bbs.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lm
 * @since 2023-01-22
 */
@Service
public class UserFollowingServiceImpl extends ServiceImpl<UserFollowingMapper, UserFollowing> implements IUserFollowingService {

    @Resource
    UserFollowingMapper userFollowingMapper;

    @Resource
    IUserService userService;
    @Override
    public Page<UserFollowingDTO> getUserFollowingPage(Page<UserFollowing> page, Wrapper<UserFollowing> wrapper) {
        return userFollowingMapper.selectUserFollowingDtoList(page, wrapper);
    }

    @Override
    public Page<UserFollowingDTO> getFansPage(Page<UserFollowing> page, Wrapper<UserFollowing> wrapper) {
        return userFollowingMapper.selectFansList(page,wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void follow(UserFollowing userFollowing, Boolean isFollow) throws Exception {

        if(isFollow) {
            boolean save = this.save(userFollowing);
            if(!save)
                throw new Exception("非法请求");
            userService.lambdaUpdate()
                    .eq(User::getUserId, userFollowing.getFollowedUser())
                    .setSql("fans_count = fans_count + 1")
                    .update();
            userService.lambdaUpdate()
                    .eq(User::getUserId, userFollowing.getUser())
                    .setSql("following_count = following_count + 1")
                    .update();

        } else  {
            boolean remove = this.lambdaUpdate().eq(UserFollowing::getUser, userFollowing.getUser())
                    .eq(UserFollowing::getFollowedUser, userFollowing.getFollowedUser())
                    .remove();
            if(!remove)
                throw new Exception("非法请求");
            userService.lambdaUpdate()
                    .eq(User::getUserId, userFollowing.getFollowedUser())
                    .setSql("fans_count = fans_count - 1")
                    .update();
            userService.lambdaUpdate()
                    .eq(User::getUserId, userFollowing.getUser())
                    .setSql("following_count = following_count - 1")
                    .update();
        }
    }
}
